<?php

require_once 'MainPageWidget.php';
class GalleryWidget extends MainPageWidget
{
	public $title = 'Галерея';
	public $pics_count = 9;

	public function Render() {

		// запросим несколько последних картинок
		$this->ctx->rh->UseClass('stores_ImageStorage');
		$img_obj = new ImageStorage( $this->ctx->store );
		$image_class_name = $this->getParam("image_class_name", "image");

		$_tdi_w = array();
		foreach($this->getParam("tdis", array()) as $n=>$tdi_oid) {
			if (is_numeric($tdi_oid)) {
				$_tdi_where = "$image_class_name.tdi_oid == $tdi_oid";
				$_tdi_w[] = $_tdi_where;
			}
		}

		$community_oid = $this->getParam('community_oid', $this->acl_assistant->acl_data['comity_oid']);
		$pics_count = intval($this->getParam("pics_count", 9));

		$ql = "objects where "
			. ($_tdi_w ? implode(" OR ", $_tdi_w)." AND " : '')
			. " $image_class_name.community_oid = :0 "
			. " AND objects.is_deleted=0 order by ctime desc "
			. ($pics_count > 0 ? "limit 0, $pics_count" : '')
			;

		$results = $this->store->find( $ql, array($community_oid) );

		$content = array();
		if ($results) {
			while ($object = $results->next()) {
				$item = array();
				$item['oid'] = $object->id;
				$item['image'] = $object->data;
				$item['image_meta'] = $img_obj->Get( $object->data['image_oid'] );
				$item['item_url'] = $this->hrefItem($object);
				$items[] = $item;
			}
			$content['items'] = $items;
		}

		$this->content = $content;
		return $this;
	}

	public function settingsForm ()
	{
		$tdis_list = $this->getTdis();
		$config['form'] = array(
			'title' => 'Список файлов',
			'fields' => array(

				'title' => array(
					'type' => 'text',
					'title' => 'Название',
					'default' => $this->title,
					'description' => 'Название меню',
				),

				'pics_count' => array(
					'type' => 'text',
					'title' => 'Количество изображений',
					'default' => $this->pics_count,
					//'description' => 'Название меню',
				),

				'tdis' => array(
					'type' => 'checklist',
					'title' => 'Список разделов',
					'description' => 'Разделы сообщества',
					'fields' => $tdis_list,
				),
			),
		);
		return $config['form'];
	}
	
	public function hrefItem ($o)
	{
		$this->ctx->rh->UseClass('RL_URLGenerator');
		$router = $this->ctx->rh->router;
		$params = $this->parent->params;
		$params['id_item'] = $o->id;
		$ug = new RL_URLGenerator($router->getRule('showitem'));
		$ug->setRouter($router);
		$ug->setParams($params);
		return $ug->generateUrl();
	} // end of method hrefFile

}

